﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web;

namespace MxTol.UI.Helpers
{
    /// <summary>
    /// 日志帮助类
    /// </summary>
    public class LogHelper
    {
        /// <summary>
        /// 异步写入日志
        /// </summary>
        /// <param name="tipMsg">错误提示信息</param>
        /// <param name="ex">异常</param>
        public static void WriteLogAsync(string tipMsg, Exception ex = null)
        {
            try
            {
                // 默认保存日志文件的目录  
                string log_root_directory = HttpRuntime.AppDomainAppPath + "Log";
                if (!Directory.Exists(log_root_directory))
                {
                    Directory.CreateDirectory(log_root_directory);
                }

                // 2014-04-13.txt
                string log_file_name = DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
                string log_file_path = log_root_directory + @"\" + log_file_name;

                // 限制日志文件大小
                if (File.Exists(log_file_path))
                {
                    FileInfo logFile = new FileInfo(log_file_path);
                    long size = logFile.Length;

                    // 最大20M
                    long maxSize = 1000 * 1000 * 20;
                    if (size > maxSize) return;
                }

                // 格式化日志信息
                string msg = string.Empty;
                if (ex != null)
                {
                    msg = "【日志时间】：{0}\r\n【提示信息】：{1}\r\n【异常信息】：{2}\r\n\r\n\r\n";
                    msg = string.Format(msg, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), tipMsg, ex.ToString());
                }
                else
                {
                    msg = "【日志时间】：{0}\r\n【提示信息】：{1}\r\n\r\n\r\n";
                    msg = string.Format(msg, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), tipMsg);
                }
                byte[] bytes = Encoding.UTF8.GetBytes(msg);

                // 异步写入日志信息
                FileStream writer = new FileStream(log_file_path, FileMode.Append, FileAccess.Write);
                writer.BeginWrite(bytes, 0, bytes.Length, new AsyncCallback(WriteCompleteHandler), writer);
            }
            catch
            {
                throw new Exception("write log message to log txt file faild");
            }
        }

        /// <summary>
        /// 日志写入完成回调函数
        /// </summary>
        private static void WriteCompleteHandler(IAsyncResult result)
        {
            using (Stream writer = (Stream)result.AsyncState)
            {
                writer.EndWrite(result);
            }
        }
    }
}
